<?php
require 'BaseAction.class.php';
import('ORG.Util.Input');
import('@.ORG.FAC');
/**
 * 用户注册登陆
 * Enter description here ...
 * @author Code.404
 *
 */

class RegAndLoginAction extends BaseAction{
	/**
	 * 用户登陆
	 * Enter description here ...
	 */
	function login(){
		if($this->_a == 'show' && $this->_t == 'dialog'){//显示ajax形式的弹出对话框
			$this->display('Index:login_dialog');
		}
		if($this->_a == 'show' && $this->_t == 'page'){//显示登录页面
			$this->display();
		}
		if($this->_a == 'exec'){//执行登录
			if( $_SESSION['verify'] != md5($_REQUEST['verifyCode'])){
				$this->ajaxReturn('VerifyError',L('VERIFY_CODE_ERROR'),0);
			}
			//验证是否为超级管理员
			if($_REQUEST['username'] == C('SUPERADMIN_ACCOUNT') && FAC::F($_REQUEST['password'] . 'code.404@!',FAC::PASSWORD) ==  C('SUPERADMIN_PASSWORD')){
				$user['id'] = 0;
				$user['username'] = C('SUPERADMIN_ACCOUNT');
				$user['role'] = 'super';
				$this->_registerSession($user);
				$this->ajaxReturn('',L('LOGIN_SUCCESS') , 1 );
			}
			//登陆验证
			$adminModel = D('Admin');
			try{
				if($adminModel->verifyUser($_REQUEST['username'] , $_REQUEST['password'])){
					$this->_registerSession($adminModel->getData());
					$this->ajaxReturn('',L('LOGIN_SUCCESS') , 1 );
				}else {
					$this->ajaxReturn('',L('LOGIN_FAILED'), 0 );
				}
			}catch (Exception $e){
				$this->ajaxReturn('',L($e->getMessage()),0);
			}
		}
	}
	/**
	 * 退出系统
	 * Enter description here ...
	 */
	public function logout(){
		unset($_SESSION['local_index']);
		unset($_SESSION['admin_login']);
		unset($_SESSION['admin_user']);
		$this->ajaxJsonReturn('200','',0,U('RegAndLogin/login'),'forward');
	}

################################### 私有方法 ##########################################
	/**
	 * 注册用户session
	 * Enter description here ...
	 * @param array $user
	 */
	private function _registerSession(Array $user){
		$_SESSION['local_index'] = $_SERVER['HTTP_HOST'] .__ROOT__;//防止多站SESSION混杂
		#用户SESSION信息
		$_SESSION['admin_login'] = true;
		$_SESSION['admin_user'] = $user;
		$_SESSION['super_admin'] = isset($user['role']) ? $user['role'] : 'none';//设置超级管理员
		
		#对用户信息进行更新操作
		if($_SESSION['super_admin'] != 'super'){
			$adminModel = D('Admin');
			
			$_map['id'] = $user['id'];
			
			$_data['last_login_time'] = time();
			$_data['last_login_ip'] = get_client_ip();
			$_data['login_count'] = $user['login_count'] + 1;
			
			$adminModel->where($_map)->save($_data);	
		}
	}
}
?>